package bag

import (
	"encoding/json"
	cs_message "sanguo/protocol/cs/message"

	"github.com/golang/protobuf/proto"
)

//武器碎片
type WeaponShard struct {
	ShardId    int32
	ShardCount int32
}

type RoleWeaponShard struct {
	WeaponShardList  map[int32]*WeaponShard
	WeaponShardDirty map[int32]bool
	dbDirty          bool
}

func (this *WeaponShard) GetWeaponShardId() int32 {
	return this.ShardId
}

func (this *RoleWeaponShard) GetWeaponShardCount(ShardId int32) int32 {
	return this.WeaponShardList[ShardId].ShardCount
}

func (this *RoleWeaponShard) GetWeaponShard(ShardId int32) *WeaponShard {
	return this.WeaponShardList[ShardId]
}

//add
func (this *RoleWeaponShard) AddWeaponShard(shardId int32, count int32) {
	v, ok := this.WeaponShardList[shardId]
	if ok {
		v.ShardCount += count
	} else {
		shard := &WeaponShard{
			ShardId:    shardId,
			ShardCount: count,
		}
		this.WeaponShardList[shard.ShardId] = shard
	}

	this.WeaponShardDirty[shardId] = true
	this.dbDirty = true
}

//use
func (this *RoleWeaponShard) UseWeaponShard(shardId int32, count int32) bool {
	shard := this.GetWeaponShard(shardId)
	if shard == nil {
		return false
	}

	if shard.ShardCount < count {
		return false
	}

	shard.ShardCount -= count
	this.WeaponShardDirty[shardId] = true
	this.dbDirty = true
	return true
}

//打包武器碎片
func (this *RoleWeaponShard) PackAllWeaponShard() []*cs_message.WeaponShard {

	ret := []*cs_message.WeaponShard{}
	for _, v := range this.WeaponShardList {
		weaponShard := &cs_message.WeaponShard{
			ShardId:    proto.Int32(v.ShardId),
			ShardCount: proto.Int32(v.ShardCount),
		}
		ret = append(ret, weaponShard)
	}
	return ret
}

func (this *RoleWeaponShard) GetWeaponShardDirtyLength() int {
	return len(this.WeaponShardDirty)
}

func (this *RoleWeaponShard) PackWeaponShardModify() []*cs_message.WeaponShard {
	ret := []*cs_message.WeaponShard{}
	for id, b := range this.WeaponShardDirty {
		if b {
			delete(this.WeaponShardDirty, id)
			v := this.WeaponShardList[id]
			weaponShard := &cs_message.WeaponShard{
				ShardId:    proto.Int32(v.ShardId),
				ShardCount: proto.Int32(v.ShardCount),
			}
			ret = append(ret, weaponShard)
		}
	}

	return ret

}

func (this *RoleWeaponShard) PackJson(fields map[string]interface{}) {
	if this.dbDirty {
		jsonStr, err := json.Marshal(this.WeaponShardList)
		if nil == err {
			fields["weaponShard"] = jsonStr
		}
	}
}

func (this *RoleWeaponShard) IsDirty() bool {
	return this.dbDirty

}

func (this *RoleWeaponShard) SetDirtyFlag() {
	this.dbDirty = true
}

func (this *RoleWeaponShard) ClearDirtyFlag() {
	this.dbDirty = false
}

func (this *RoleWeaponShard) Init(weaponShards map[int32]*WeaponShard) {
	this.WeaponShardList = weaponShards
	this.WeaponShardDirty = map[int32]bool{}
	this.dbDirty = false
}
